﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using KC.Presentation.ProcessAggregator.Plugins;
using KC.DataAccess.Processor;
using BLL = KC.Business.Processor;

namespace KC.Presentation.ProcessAggregator
{
	public partial class ProcessAggregatorUI : Form
	{
		public ProcessAggregatorUI()
		{
			InitializeComponent();
		}

		private ProcessorDataContext dc;

		private void Form1_Load(object sender, EventArgs e)
		{
			dc = new ProcessorDataContext(System.Configuration.ConfigurationManager.ConnectionStrings["Processor"].ConnectionString);
			timer1.Start();

			BLL.Processor.AddDetail(ref dc, "Starting up");
			LoadPlugins();
			BLL.Processor.AddDetail(ref dc, "Startup complete");
		}

		private void LoadMain()
		{
			txtErrors.Text = "";
			var errors = (from e in dc.Errors
						  orderby e.ID descending
						  select e).Take(100);
			foreach (Error error in errors)
				txtErrors.Text += error.Datetime.ToString("MM/dd/yy HH:mm:ss") + " | " + error.Message.Replace("\r", " ").Replace("\n", " ") + "\r\n";

			txtDetails.Text = "";
			var details = (from d in dc.Details
						   orderby d.ID descending
						   select d).Take(100);
			foreach (Detail detail in details)
				txtDetails.Text += detail.datetime.ToString("MM/dd/yy HH:mm:ss") + " | " + detail.text.Replace("\r", " ").Replace("\n", " ") + "\r\n";
		}
		private void LoadPlugins()
		{
			string path = System.Reflection.Assembly.GetAssembly(typeof(RssPlugin)).CodeBase;
			BLL.Processor.AddDetail(ref dc, "Loading display plugins from: " + path);

			List<BLL.DisplayPluginBase> plugins = BLL.Processor.GetDisplayPlugins(System.IO.Path.GetDirectoryName(Application.ExecutablePath));
			BLL.Processor.AddDetail(ref dc, plugins.Count.ToString() + " display plugins detected.");
			
			foreach (BLL.DisplayPluginBase plugin in plugins)
			{
				BLL.Processor.AddDetail(ref dc, "Loading display plugin: " + plugin.Title ?? "(Untitled)");
				TabPage page = new TabPage();
				plugin.userControl.Dock = DockStyle.Fill;
				page.Controls.Add(plugin.userControl);
				page.Text = plugin.Title;
				tabControl1.TabPages.Add(page);
			}
		}

		private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
		{
			MessageBox.Show("Process Aggregator\r\nProject Codename: Universus\r\n\r\nCopyright Kevin Connolly // Deviant Innovations // 2011");
		}

		private void timer1_Tick(object sender, EventArgs e)
		{
			LoadMain();
		}

	}
}
